import React, { useState, useEffect } from 'react';
import { 
  Drawer, 
  List, 
  Input, 
  Tag as AntdTag, 
  Spin, 
  Empty, 
  message, 
  Select, 
  Pagination,
  Radio,
  Space,
  Button,
  Divider,
  Checkbox
} from 'antd';
import { SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import styles from './ProblemList.module.css';
import { problemService } from '@/services/problemService';
import { problemSetService } from '@/services/problemSetService';
import { Problem } from '@/types/problem';
import { ProblemSetProblem } from '@/types/problemSet';
import { Tag } from '@/services/tagService';
import { getDifficultyTag } from '@/utils/difficulty';

interface ProblemListProps {
  visible: boolean;
  onClose: () => void;
  contest_id?: string | null;
  origin?: string | null; // 新增：origin参数
  problemSetId?: string | null; // 新增：题单ID参数
}

const ProblemList: React.FC<ProblemListProps> = ({ visible, onClose, contest_id, origin, problemSetId }) => {
  const [problems, setProblems] = useState<Problem[]>([]);
  const [filteredProblems, setFilteredProblems] = useState<Problem[]>([]);
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalProblems, setTotalProblems] = useState(0);
  const [selectedDifficulty, setSelectedDifficulty] = useState<string>('all');
  const [allTags, setAllTags] = useState<Tag[]>([]);
  const [selectedTagIds, setSelectedTagIds] = useState<number[]>([]);
  const [showFilters, setShowFilters] = useState(false);
  
  const navigate = useNavigate();

  useEffect(() => {
    if (visible) {
      fetchProblems(1, searchText);
    }
  }, [visible, contest_id, origin, problemSetId]);

  // 筛选功能现在由后端处理，不再需要这个useEffect

  const fetchProblems = async (page = 1, searchKeyword = '') => {
    setLoading(true);
    try {
      if (origin === 'problemset' && problemSetId) {
        // 题单题库：使用专门的API获取题单中的题目
        const response = await problemSetService.getProblemSetProblems(Number(problemSetId));
        
        if (response.data) {
          // 将ProblemSetProblem转换为Problem格式
          const problemList = (response.data.data as any).map((psp: ProblemSetProblem) => ({
            id: psp.problem.id,
            _id: psp.problem._id,
            title: psp.problem.title,
            difficulty: psp.problem.difficulty,
            tags: [], // 题单中的题目可能没有标签信息
            user_status: psp.user_status,
            // 其他必要字段
            visible: true,
            description: '',
            input_description: '',
            output_description: '',
            samples: [],
            hint: '',
            source: '',
            time_limit: psp.problem.time_limit,
            memory_limit: psp.problem.memory_limit,
            spj: false,
            rule_type: 'ACM' as const,
            test_case_score: [],
            template: {},
            languages: [],
            io_mode: {
              io_mode: 'Standard IO' as const
            },
            submission_number: psp.problem.submission_number,
            accepted_number: psp.problem.accepted_number
          } as Problem));
          
          setProblems(problemList);
          setFilteredProblems(problemList);
          setTotalProblems(problemList.length);
          setCurrentPage(1);
          
          // 提取所有唯一标签（题单中的题目可能没有标签）
          setAllTags([]);
        }
      } else {
        // 系统题库和比赛题库：使用problemService.getProblems
        const params: any = {
          page,
          limit: pageSize
        };
        
        if (contest_id) {
          params.contest_id = Number(contest_id);
        }
        
        // 根据origin参数设置查询条件
        if (origin === 'contest' && contest_id) {
          // 比赛题库：获取指定比赛的题目
          params.contest_id = Number(contest_id);
        } else if (origin === 'system') {
          // 系统题库：获取contest_id为空的题目
          params.contest_id = null;
        }
        
        if (searchKeyword) {
          params.keyword = searchKeyword;
        }
        
        const response = await problemService.getProblems(params);
        
        if (response.data) {
          const problemData = 'data' in response.data ? response.data.data : response.data;
          const problemList = problemData.results || [];
          
          // 确保题目列表是有效的
          const validProblems = problemList.filter((p: any) => p && typeof p === 'object' && p.id);
          
          setProblems(validProblems);
          setFilteredProblems(validProblems);
          setTotalProblems(problemData.count || 0);
          setCurrentPage(problemData.current_page || 1);
          
          // 提取所有唯一标签
          const tagsMap = new Map<number, Tag>();
          validProblems.forEach((problem: any) => {
            if (problem.tags && Array.isArray(problem.tags)) {
              problem.tags.forEach((tag: any) => {
                if (tag && typeof tag === 'object' && 'id' in tag && 'name' in tag) {
                  tagsMap.set(tag.id, tag as Tag);
                }
              });
            }
          });
          setAllTags(Array.from(tagsMap.values()).sort((a, b) => a.name.localeCompare(b.name)));
        }
      }
    } catch (error) {
      console.error('获取题目列表失败:', error);
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 筛选功能现在由后端处理，不再需要前端筛选逻辑

  const handleSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value;
    setSearchText(value);
    // 延迟搜索，避免频繁请求
    setTimeout(() => {
      fetchProblems(1, value);
    }, 500);
  };

  const handleProblemClick = (problemId: number) => {
    // 构建跳转URL，保持origin参数
    const params = new URLSearchParams();
    if (contest_id) params.set('contest_id', contest_id);
    if (origin) params.set('origin', origin);
    if (problemSetId) params.set('problemSetId', problemSetId);
    const queryString = params.toString();
    navigate(`/problem/${problemId}/submit${queryString ? `?${queryString}` : ''}`);
    onClose();
  };

  const handlePageChange = (page: number, newPageSize?: number) => {
    if (newPageSize && newPageSize !== pageSize) {
      setPageSize(newPageSize);
      fetchProblems(1, searchText);
    } else {
      fetchProblems(page, searchText);
    }
  };

  const handleDifficultyChange = (value: string) => {
    setSelectedDifficulty(value);
    // 重新请求数据
    fetchProblems(1, searchText);
  };

  const handleTagChange = (checkedValues: number[]) => {
    setSelectedTagIds(checkedValues);
    // 重新请求数据
    fetchProblems(1, searchText);
  };

  const resetFilters = () => {
    setSelectedDifficulty('all');
    setSelectedTagIds([]);
    setSearchText('');
    // 重新请求数据
    fetchProblems(1, '');
  };

  // 获取抽屉标题
  const getDrawerTitle = () => {
    if (contest_id) return "比赛题目列表";
    if (origin === 'contest') return "比赛题库";
    if (origin === 'problemset') return "题单题库";
    if (origin === 'system') return "系统题库";
    return "题库列表";
  };

  // 直接使用后端返回的题目列表
  const currentProblems = filteredProblems;

  return (
    <Drawer
      title={getDrawerTitle()}
      placement="left"
      onClose={onClose}
      open={visible}
      width={350}
      className={styles.problemDrawer}
    >
      <div className={styles.searchContainer}>
        <Input
          placeholder="搜索题目编号或标题"
          prefix={<SearchOutlined />}
          value={searchText}
          onChange={handleSearch}
          allowClear
        />
        <Button 
          icon={<FilterOutlined />} 
          onClick={() => setShowFilters(!showFilters)}
          type={showFilters ? "primary" : "default"}
          className={styles.filterButton}
        >
          筛选
        </Button>
      </div>

      {showFilters && (
        <div className={styles.filtersContainer}>
          <Divider orientation="left">难度</Divider>
          <Radio.Group 
            value={selectedDifficulty} 
            onChange={(e) => handleDifficultyChange(e.target.value)}
            className={styles.difficultyFilter}
            buttonStyle="solid"
          >
            <Radio.Button value="all">全部</Radio.Button>
                          <Radio.Button value="Low">
                <div className={styles.difficultyOption}>
                  {getDifficultyTag('Low')}
                </div>
              </Radio.Button>
              <Radio.Button value="Mid">
                <div className={styles.difficultyOption}>
                  {getDifficultyTag('Mid')}
                </div>
              </Radio.Button>
              <Radio.Button value="High">
                <div className={styles.difficultyOption}>
                  {getDifficultyTag('High')}
                </div>
              </Radio.Button>
          </Radio.Group>

          <Divider orientation="left">标签</Divider>
          <div className={styles.tagsContainer}>
            <Checkbox.Group 
              options={allTags.map(tag => ({ label: tag.name, value: tag.id }))} 
              value={selectedTagIds}
              onChange={handleTagChange}
              className={styles.tagCheckboxGroup}
            />
          </div>

          <div className={styles.filterActions}>
            <Button onClick={resetFilters}>重置筛选</Button>
          </div>
        </div>
      )}

      {loading ? (
        <div className={styles.loadingContainer}>
          <Spin size="large" />
        </div>
      ) : filteredProblems.length > 0 ? (
        <>
          <div className={styles.problemListHeader}>
            <span>共找到 <strong>{totalProblems}</strong> 道题目</span>
          </div>
          <div className={styles.problemList}>
            <List
              dataSource={currentProblems}
              renderItem={(problem) => (
                <div 
                  className={styles.problemItem}
                  onClick={() => handleProblemClick(problem.id)}
                >
                  <div className={styles.problemInfo}>
                    <div className={styles.problemTitle}>
                      <span className={styles.problemId}>
                        {problem.user_status === true ? (
                          <AntdTag color="success" style={{ margin: 0, border: 'none' }}>
                            {problem._id}
                          </AntdTag>
                        ) : problem.user_status === false ? (
                          <AntdTag color="error" style={{ margin: 0, border: 'none' }}>
                            {problem._id}
                          </AntdTag>
                        ) : (
                          <AntdTag style={{ margin: 0, border: '1px solid #d9d9d9', backgroundColor: 'transparent', color: '#666' }}>
                            {problem._id}
                          </AntdTag>
                        )}
                      </span>
                      <span className={styles.titleText}>{problem.title}</span>
                    </div>
                    <div className={styles.problemMeta}>
                      <div className={styles.problemTags}>
                        {problem.tags && Array.isArray(problem.tags) && problem.tags.slice(0, 2).map((tag: any, index: number) => (
                          tag && typeof tag === 'object' && 'id' in tag && 'name' in tag ? (
                            <AntdTag key={tag.id}>{tag.name}</AntdTag>
                          ) : null
                        ))}
                        {problem.tags && Array.isArray(problem.tags) && problem.tags.length > 2 && (
                          <AntdTag>+{problem.tags.length - 2}</AntdTag>
                        )}
                      </div>
                      {getDifficultyTag(problem.difficulty)}
                    </div>
                  </div>
                </div>
              )}
            />
            <div className={styles.paginationContainer}>
              <div className={styles.paginationRow}>
                <Pagination
                  current={currentPage}
                  pageSize={pageSize}
                  total={totalProblems}
                  onChange={handlePageChange}
                  showSizeChanger={false}
                  showQuickJumper={false}
                  pageSizeOptions={['20', '50', '100']}
                />
              </div>
              <div className={styles.paginationControls}>
                <span className={styles.pageSizeLabel}>每页显示：</span>
                <Select
                  value={pageSize}
                  onChange={(value) => handlePageChange(1, value)}
                  style={{ width: 80, marginRight: 16 }}
                >
                  <Select.Option value={10}>10</Select.Option>
                  <Select.Option value={20}>20</Select.Option>
                  <Select.Option value={50}>50</Select.Option>
                </Select>
                <span className={styles.jumpLabel}>跳转到：</span>
                <Input
                  placeholder="页码"
                  style={{ width: 60 }}
                  onPressEnter={(e) => {
                    const page = parseInt((e.target as HTMLInputElement).value);
                    if (page && page > 0 && page <= Math.ceil(totalProblems / pageSize)) {
                      handlePageChange(page);
                    }
                  }}
                />
              </div>
            </div>
          </div>
        </>
      ) : (
        <Empty description="没有找到匹配的题目" />
      )}
    </Drawer>
  );
};

export default ProblemList; 